package day12;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.util.List;

/**
 * @author oldliu
 * @since 1.0
 */
public class XMLOperate {
    //增删改查
    public static void main(String[] args) throws DocumentException {
        //dom方式
        //read();
        //searchByItem(3);
        //searchByTime("3周");
        //addNewBook(4,"mysql数据库高级操作","2周","mysql的日常操作和Sql写法");
        //modifyBook(4, "mysql数据库入门", "1.5周", "mysql的管理和sql语法");

        //delete("java程序基础");
        add2(0,"预科","2周以上","介绍硬件基础");
    }

    public static void read() throws DocumentException {
        //构建一个阅读器
        SAXReader reader = new SAXReader();
        //获得Document对象
        Document document = reader.read(new File("E:\\java_workspace\\IdeaProjects\\java82\\java高级\\src\\java82.xml"));
        Element root = document.getRootElement();
        System.out.println(root.getName());
        System.out.println("值：" + root.getTextTrim());
        //》》》List elements = root.elements();//所有的子节点
        //从当前的根节点开始找
        List<Element> list = root.selectNodes("book");
        for (Element e : list) {
            //访问e的属性,都是字符串。。。
            String item = e.attributeValue("item");
            int i = Integer.parseInt(item);
            //Element ename = (Element) e.selectNodes("name").get(0);
            Element ename = (Element) e.selectSingleNode("name");//查找唯一子节点
            String name = ename.getTextTrim();//!
            String time = ((Element) (e.selectSingleNode("time"))).getTextTrim();
            String desc = ((Element) (e.selectSingleNode("desc"))).getTextTrim();
            System.out.printf("这本书的信息是%d,name=%s,时间 %s,介绍 %s\n", i, name, time, desc);
        }
    }

    //根据item的值查找book信息
    public static void searchByItem(int itemid) throws DocumentException {
//构建一个阅读器
        SAXReader reader = new SAXReader();
        //获得Document对象
        Document document = reader.read(new File("E:\\java_workspace\\IdeaProjects\\java82\\java高级\\src\\java82.xml"));

        List<Element> list = document.selectNodes("/books/book[@item=" + itemid + "]");
        if (list.size() == 0) {
            System.out.println("没有这个item的书籍信息");
            return;
        }
        System.out.println("查找的结果如下：");
        for (Element e : list) {
            //访问e的属性,都是字符串。。。
            String item = e.attributeValue("item");
            int i = Integer.parseInt(item);
            //Element ename = (Element) e.selectNodes("name").get(0);
            Element ename = (Element) e.selectSingleNode("name");//查找唯一子节点
            String name = ename.getTextTrim();//!
            String time = ((Element) (e.selectSingleNode("time"))).getTextTrim();
            String desc = ((Element) (e.selectSingleNode("desc"))).getTextTrim();
            System.out.printf("这本书的信息是 编号是 %d,name=%s,时间 %s,介绍 %s\n", i, name, time, desc);

        }
    }

    //根据item的值查找book信息
    public static void searchByTime(String timeWeek) throws DocumentException {
//构建一个阅读器
        SAXReader reader = new SAXReader();
        //获得Document对象
        Document document = reader.read(new File("E:\\java_workspace\\IdeaProjects\\java82\\java高级\\src\\java82.xml"));

        List<Element> list = document.selectNodes("/books/book[time='" + timeWeek + "']");

        if (list.size() == 0) {
            System.out.println("没有这个item的书籍信息");
            return;
        }
        System.out.println("查找的结果如下：");
        for (Element e : list) {
            //访问e的属性,都是字符串。。。
            String item = e.attributeValue("item");
            int i = Integer.parseInt(item);
            //Element ename = (Element) e.selectNodes("name").get(0);
            Element ename = (Element) e.selectSingleNode("name");//查找唯一子节点
            String name = ename.getTextTrim();//!
            String time = ((Element) (e.selectSingleNode("time"))).getTextTrim();
            String desc = ((Element) (e.selectSingleNode("desc"))).getTextTrim();
            System.out.printf("这本书的信息是 编号是 %d,name=%s,时间 %s,介绍 %s\n", i, name, time, desc);

        }
    }

    //加新书
    public static void addNewBook(int id, String name, String time, String desc) {
        SAXReader reader = new SAXReader();
        //获得Document对象
        try {
            Document document = reader.read(new File("E:\\java_workspace\\IdeaProjects\\java82\\java高级\\src\\java82" +
                    ".xml"));
            Element root = document.getRootElement();
            //新建一个book节点
            Element ebook = root.addElement("book");
            ebook.addAttribute("item", String.valueOf(id));
            Element ename = ebook.addElement("name");
            ename.setText(name);
            ebook.addElement("time").setText(time);
            ebook.addElement("desc").setText(desc);
            //写回到xml文件中
            //控制格式和字符集
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            XMLWriter xm = new XMLWriter(new FileOutputStream("E:\\java_workspace\\IdeaProjects\\java82\\java高级\\src" +
                    "\\java82.xml"), format);
            xm.write(document);
            xm.close();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }


    }

    //根据id,修改书籍的其他信息
    public static void modifyBook(int id, String name, String time, String desc) {
        SAXReader reader = new SAXReader();
        //获得Document对象
        try {
            Document document = reader.read(new File("E:\\java_workspace\\IdeaProjects\\java82\\java高级\\src\\java82" +
                    ".xml"));
            Element ebook = (Element) document.selectSingleNode("/books/book[@item=" + id + "]");
            if (ebook == null) {
                System.out.println("没有这本书");
                return;
            }
            ebook.selectSingleNode("name").setText(name);
            ebook.selectSingleNode("time").setText(time);
            ebook.selectSingleNode("desc").setText(desc);

            //写回到xml文件中
            //控制格式和字符集
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            XMLWriter xm = new XMLWriter(new FileOutputStream("E:\\java_workspace\\IdeaProjects\\java82\\java高级\\src" +
                    "\\java82.xml"), format);
            xm.write(document);
            xm.close();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }


    }

    //删除一本书
    public static void delete(String name) {
        SAXReader reader = new SAXReader();
        //获得Document对象

        try {
            Document document = reader.read(new File("E:\\java_workspace\\IdeaProjects\\java82\\java高级\\src\\java82" +
                    ".xml"));
            List<Element> books = document.selectNodes("/books/book[name='" + name + "']");
            if(books.size()==0){
                System.out.println("没有 "+name+" 这本书！");
                return;
            }
            for(Element e:books){
                e.getParent().remove(e);
            }

            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            XMLWriter xm = new XMLWriter(new FileOutputStream("E:\\java_workspace\\IdeaProjects\\java82\\java高级\\src" +
                    "\\java82.xml"), format);
            xm.write(document);
            xm.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //增加，考虑document有异常
    public static void add2(int id,String name,String time,String desc){
        final  String fileName="java-books.xml";
        SAXReader reader = new SAXReader();
        //获得Document对象
        Document document=null;
        try {
             document = reader.read(new File(fileName));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("新建一个Document对象");
            document= DocumentHelper.createDocument();//!!!!
            Element books = document.addElement("books");
            books.addAttribute("type","学士后8.0");
            books.addAttribute("company","Jade Bird");
        }
        //
        Element root = document.getRootElement();
        //新建一个book节点
        Element ebook = root.addElement("book");
        ebook.addAttribute("item", String.valueOf(id));
        Element ename = ebook.addElement("name");
        ename.setText(name);
        ebook.addElement("time").setText(time);
        ebook.addElement("desc").setText(desc);
        //写回到xml文件中
        //控制格式和字符集
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        try {
            XMLWriter xm = new XMLWriter(new FileOutputStream(fileName), format);
            xm.write(document);
            xm.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
